﻿using DataBase.Utils;
using GreenXi.Model;
using GreenXi.Pages.Power;
using Microsoft.EntityFrameworkCore;
using Prism.Commands;
using Prism.Mvvm;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using static GreenXi.App;

namespace GreenXi.ViewModel
{


    public class UserViewModel : BindableBase
    {
        public static UserEdit userEdit;
        //新增用户
        private DelegateCommand _AddUser;

        public DelegateCommand<object> SaveColumn { get; set; }
        public DelegateCommand<object> CloseWindows { get; set; }

        public DelegateCommand AddUser
        {
            get
            {
                _AddUser ??= new DelegateCommand(AddUser_Click);
                return _AddUser;
            }
        }
        //编辑用户

        private DelegateCommand _EditUser;
        public DelegateCommand EditUser
        {
            get
            {
                _EditUser ??= new DelegateCommand(EditUser_Click);
                return _EditUser;
            }
        }


        private DelegateCommand _DelUser;
        public DelegateCommand DelUser
        {
            get
            {
                _DelUser ??= new DelegateCommand(DelUser_Click);
                return _DelUser;
            }
        }

        public void AddUser_Click()
        {
            SelectUser = new User();
            userEdit = new();
            userEdit.DataContext = this;
            userEdit.ShowDialog();
        }

        public void EditUser_Click()
        {
            if (SelectUser == null)
            {
                MessageBox.Show("请先选择用户！");
                return;
            }
            userEdit = new();
            userEdit.DataContext = this;
            userEdit.ShowDialog();
        }
        public void DelUser_Click()
        {
            if (SelectUser == null)
            {
                MessageBox.Show("请先选择用户！");
                return;
            }
          
            DataBase.User user = MyDbContext.Instance.Users.Where(x => x.UserID == SelectUser.ID).FirstOrDefault();
            if (user != null) {
                MyDbContext.Instance.Users.Remove(user);
                MyDbContext.Instance.SaveChanges();

                UpdateInfo();

            }

            MessageBox.Show("删除成功！");
        }
        public void SaveColumn_Click(object parm)
        {
            using MyDbContext myDbContext = new();
            if (SelectUser == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(SelectUser.UserName) || string.IsNullOrEmpty(SelectUser.PassWord))
            {
                MessageBox.Show("用户名或密码不能为空！");
                return;
            }
            if (SelectUser.ID == 0)
            {
                DataBase.User user = new DataBase.User();
                user.UserName = SelectUser.UserName;
                user.Password = SelectUser.PassWord;
                user.Remark = SelectUser.Remark;
                user.IsEnabled = 1;
                user.CreatedTime = DateTime.Now;
                myDbContext.Users.Add(user); ;
                myDbContext.SaveChanges();
                MessageBox.Show("添加成功！");
            }
            else
            {
                var user = MyDbContext.Instance.Users.FirstOrDefault(u => u.UserID == SelectUser.ID);
                if (user != null)
                {
                    user.UserName = SelectUser.UserName;
                    user.Remark = SelectUser.Remark;
                    user.Password = SelectUser.PassWord;
                    user.ModifiedTime = DateTime.UtcNow.AddHours(8);
                    myDbContext.SaveChanges();
                    MessageBox.Show("修改成功！");
                }
            }
            userEdit.Close();

            UpdateInfo();
        }

        private void CloseWindows_Click()
        {
            userEdit.Close();//关闭弹窗
        }
        //日志
        private readonly ILogger logger;

        #region 页面元素
        //表格内容
        private ObservableCollection<User>? _userList;
        public ObservableCollection<User>? UserList
        {
            get { return _userList; }
            set { SetProperty(ref _userList, value); }
        }
        public List<string>? RoleGroupList { get; set; }
        //当前选择的内容
        private User? _selectUser;
        public User? SelectUser
        {
            get { return _selectUser; }
            set
            {
                if (_selectUser != value)
                {
                    SetProperty(ref _selectUser, value);
                }
            }
        }
        //保存按钮绑定的指令
        public ICommand SaveUserInfoCommand { get; }
        #endregion

        #region 数据初始化 
        public UserViewModel()
        {
            UpdateInfo();
            SaveUserInfoCommand = new DelegateCommand(() => UpdateUserInfo(SelectUser));
            logger = new LoggerConfiguration().CreateLogger();

            SaveColumn = new DelegateCommand<object>((p) => { SaveColumn_Click(p); });//保存栏目

            CloseWindows = new DelegateCommand<object>((p) => { CloseWindows_Click(); });//关闭编辑窗口
        }

        //更新表格内容
        public void UpdateInfo()
        {
            //获取小于等于当前登录用户权重的用户信息
            var users = CurrentUser.GetUserInfoByCurrentUserWeight();

            //将获取到的用户信息转换为User对象，并添加到 UserList 中
            UserList = new ObservableCollection<User>(users.Select(x => new User()
            {
                ID = x.UserID,
                UserName = x.UserName,
                CreatedTime = x.CreatedTime,
                Remark = x.Remark,
                RoleGroup = GetPermissionCode(x.UserName) ?? "", // 使用安全导航运算符和空合并运算符处理可能的null值
                IsEnabled = 1,
                PassWord=x.Password
                
            }));

            RoleGroupList = CurrentUser.GetRoleGroupList();
        }

        //获取用户的PermissionCode
        public static string GetPermissionCode(string userName)
        {
            string res = "";

            int userId = MyDbContext.Instance.Users
                .Where(x => x.UserName == userName)
                .Select(x => x.UserID)
                .FirstOrDefault();

            int? roleId = MyDbContext.Instance.UserRoleRelations
                .Where(x => x.UserId == userId)
                .Select(x => (int?)x.RoleId)
                .FirstOrDefault();

            res = MyDbContext.Instance.RolePermissions
                .FirstOrDefault(x => x.RoleID == roleId)
                ?.PermissionCode ?? "PermissionCode没找到";
            return res;
        }

        /// <summary>
        /// 更新User表的内容
        /// </summary>
        /// <param name="SelectUser">当前选择的表格的内容（要保存的User对象）</param>
        private void UpdateUserInfo(User SelectUser)
        {
            try
            {

                //考虑没有选中对象的情况
                if (SelectUser != null)
                {
                    var userId = SelectUser.ID;
                    var user = MyDbContext.Instance.Users.FirstOrDefault(u => u.UserID == userId);
                    if (user != null)
                    {
                        user.UserName = SelectUser.UserName;
                        user.Remark = SelectUser.Remark;
                        user.ModifiedTime = DateTime.UtcNow.AddHours(8);
                        user.CreatedTime = SelectUser.CreatedTime;
                        //获取当前角色本身的权限
                        var roleId_before = MyDbContext.Instance.UserRoleRelations
                            .Where(x => x.UserId == userId)
                            .Select(x => x.RoleId)
                            .FirstOrDefault();
                        var PermissionCode_before = MyDbContext.Instance.RolePermissions
                            .Where(x => x.RoleID == roleId_before)
                            .Select(x => x.PermissionCode)
                            .FirstOrDefault();
                        var PermissionCode = SelectUser.RoleGroup;
                        //更新权限，不允许将操作自己的权限，只允许去操作他人的
                        if (userId == CurrentUser.UserId && PermissionCode_before != PermissionCode)
                        {
                            MessageBox.Show("不允许更改自己的权限！");
                        }
                        else
                        {
                            //获取PermissionCode对应的roleId
                            var roleId = MyDbContext.Instance.RolePermissions
                                .Where(x => x.PermissionCode == PermissionCode)
                                .Select(x => x.RoleID)
                                .FirstOrDefault();
                            //获取UserRoleRelations对应的对象
                            var userRoleRelation = MyDbContext.Instance.UserRoleRelations.FirstOrDefault(x => x.UserId == userId);
                            if (userRoleRelation != null)
                            {
                                userRoleRelation.RoleId = roleId;
                            }
                            MyDbContext.Instance.SaveChanges();
                            UpdateInfo();
                            MessageBox.Show("更新成功！");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新失败！");
                // 记录错误日志
                logger.Error(ex, "更新操作异常：");
            }
        }
        #endregion

    }

}


